import React, { useState } from "react";
import "./TodoHeader.css";
import { useDispatch } from "react-redux";
import { asyncAddTodo } from "../../../app/slices/todoSlice";
export default function TodoHeader() {
  let [v, setV] = useState("");
  //获取 dispatch 函数
  let dispatch = useDispatch();
  return (
    <div className="todo-header">
      <input
        onKeyUp={async (e) => {
          //判断是否为回车键
          if (e.code === "Enter") {
            try {
              //新增
              await dispatch(asyncAddTodo(v));
              //清空
              setV("");
              alert("添加成功");
            } catch (e) {
              alert('添加失败');
            }
          }
        }}
        value={v}
        onChange={(e) => {
          setV(e.target.value);
        }}
        type="text"
        placeholder="请输入你的任务名称，按回车键确认"
      />
    </div>
  );
}
